package br.com.lsi.dao;

import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.transaction.SystemException;
import javax.transaction.Transaction;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import br.com.lsi.Util.HibernateUtil;

public abstract class GenericDao<T> implements Serializable {

	private Session session;
	private Transaction trans;
	private Class<T> classe;
	private List<T> lista = new ArrayList<T>();
	private Logger logger = Logger.getLogger(GenericDao.class);
	
	public GenericDao(Class<T> classe) {
		this.classe = classe;
	}

	public void salvar(T generic) throws IllegalStateException, SystemException {			
			try {
				this.trans = (Transaction) getCurrentSession().beginTransaction();
				getCurrentSession().save(generic);
			} catch (Exception e) {				
				this.trans.rollback();
				logger.debug("problemas no metodo salvar");
				e.printStackTrace();				
			}
		 }

	public void remover(T generic) throws Exception {
		try {
			T novo = buscar(generic);
			this.trans = (Transaction) getCurrentSession().beginTransaction();
			getCurrentSession().delete(novo);			
		} catch (Exception e) {
			logger.info("");
			throw e;
			
		}
	}
	public T buscar(T entity) {

		long id = entity.hashCode();
		for (T t : lista) {

			if (id == t.hashCode())
				entity = t;
		}
		return entity;
	}

	public void alterar(T generic) {
		T novo = buscar(generic);
		try {
			trans = (Transaction) getCurrentSession().beginTransaction();
			getCurrentSession().update(novo);
			getCurrentSession().flush();
		} catch (Exception e) {
			// TODO: handle exception
		} 
	}

	public List<T> listar(T generic) throws IllegalStateException,
			SystemException {
		try {
			List<T> list = getCurrentSession().createCriteria(classe).list();
			lista = list;
		} catch (Exception e) {
			trans.rollback();
		}
		return lista;
	}

	public Session getCurrentSession() {
		return this.session;
	}
	
	public void openSession() {
		this.session = HibernateUtil.getSessionFactory().openSession();
	}
	
	public void closedSession() {
		getCurrentSession().close();
	}
	public Transaction Commit() {
		return this.trans;
	}
}
